package com.code.leetcode.offer;

import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;

/**
 * @author codeDorado
 * @version 1.0
 * @date 2020/8/2 15:26
 */
public class The40 {
    public int[] getLeastNumbers(int[] arr, int k) {
        Queue<Integer> queue = new PriorityQueue<>((v1, v2) -> v2 - v1);
        if (arr == null || arr.length < 1 || k == 0) return new int[]{};

        for (int i = 0; i < k; i++) queue.add(arr[i]);
        for (int i = k; i < arr.length; i++) {
            if (queue.peek() > arr[i]) {
                queue.poll();
                queue.add(arr[i]);
            }
        }

        int size = queue.size();
        int[] rtn = new int[queue.size()];
        for (int i = 0; i < size; i++) {
            rtn[i] = queue.poll();
        }
        return rtn;
    }

    public static void main(String[] args) {
        The40 the40 = new The40();
        the40.getLeastNumbers(new int[]{3,2,1}, 2);
    }
}
